﻿using System;
using System.Collections.Generic;
using System.Text;
using Boomerang.Common.Sms.BoomerangService;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;

namespace Boomerang.Common.Sms
{
    public class SmsConnection
    {
        private SmsConnectionOptions options;
        private SOAP12 service;

        public SmsConnection(SmsConnectionOptions options)
        {
            this.options = options;
        }

        public string BoomerangUserName
        {
            get { return options.BoomerangUserName; }
        }

        public string BoomerangPassword
        {
            get { return options.BoomerangPassword; }
        }

        public string LicenseKey
        {
            get { return options.LicenseKey; }
        }

        public SOAP12 Service
        {
            get
            {
                if (service == null)
                    service = CreateService(options);
                return service;
            }
        }

        private static SOAP12 CreateService(SmsConnectionOptions options)
        {
            SOAP12 service = new SOAP12();
            service.Url = options.GetBoomerangServiceUrl();
            service.Credentials = options.GetBoomerangCredentials();
            if (options.UseHttps)
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(TrustAllCertificateCallback);
            }

            return service;
        }

        private static bool TrustAllCertificateCallback(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors errors)
        {
            return true;
        }

        public bool Test()
        {
            return !string.IsNullOrEmpty(Service.GetDisclaimer(this.options.BoomerangUserName, this.options.BoomerangPassword, this.options.LicenseKey));
        }
    }

}
